﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿using DeviceCommons;
using DeviceCommons.DeviceMessages.Builders;
using DeviceCommons.DeviceMessages.Enums;
using DeviceCommons.DeviceMessages.Serialization;
using DeviceCommons.DeviceMessages.Models;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Text;
using DeviceCommons.DeviceMessages.Models.V1;
using ConsoleTestApp;

namespace DeviceDataGenerator
{
    /// <summary>
    /// DeviceCommons 性能测试控制台
    /// 随机构建消息并测试各种场景下的性能指标
    /// </summary>
    class Program
    {
        private static readonly Random _random = new Random();
        private static readonly DeviceMessageSerializer _serializer = new DeviceMessageSerializer();
        private static readonly DeviceMessageParser _parser = new DeviceMessageParser();

        // 性能统计
        private static PerformanceStats _stats = new PerformanceStats();
        private static readonly object _statsLock = new object();
        
        // 测试开始时间（用于生成测试记录）
        private static DateTime _testStartTime;

        // 系统资源监控
        private static SystemResourceMonitor? _resourceMonitor;

        // 配置
        private static PerformanceTestSettings _settings = DefaultConfig.GetDefault();

        static async Task Main(string[] args)
        {
            // 检查是否运行简单测试
            if (args.Length > 0 && args[0].ToLower() == "test")
            {
                SimpleTest.RunTest();
                return;
            }
            
            // 检查是否运行分段统计演示
            if (args.Length > 0 && args[0].ToLower() == "demo")
            {
                QuickStatsTest.RunDemo();
                return;
            }
            
            // 检查是否运行测试记录演示
            if (args.Length > 0 && args[0].ToLower() == "record")
            {
                TestRecordDemo.RunDemo();
                return;
            }
            
            // 检查是否运行表格显示演示
            if (args.Length > 0 && args[0].ToLower() == "table")
            {
                TableDisplayDemo.RunDemo();
                return;
            }
            
            // 检查是否运行表格对齐验证
            if (args.Length > 0 && args[0].ToLower() == "verify")
            {
                TableAlignmentVerify.RunVerification();
                return;
            }
            
            // 检查是否运行性能修复验证
            if (args.Length > 0 && args[0].ToLower() == "fix")
            {
                PerformanceFixVerification.RunVerification();
                return;
            }
            
            // 检查是否运行AES性能测试
            if (args.Length > 0 && args[0].ToLower() == "aes")
            {
                AesPerformanceTest.RunPerformanceComparison();
                return;
            }
            
            // 检查是否运行AES模式配置演示
            if (args.Length > 0 && args[0].ToLower() == "config")
            {
                AesModeConfigurationDemo.RunDemo();
                return;
            }
            
            // 检查是否运行构造器AES模式演示
            if (args.Length > 0 && args[0].ToLower() == "builder")
            {
                BuilderAesModeDemo.RunDemo();
                return;
            }
            
            // 检查是否运行设备状态配置演示
            if (args.Length > 0 && args[0].ToLower() == "state")
            {
                DeviceStateConfigurationDemo.RunDemo();
                DeviceStateConfigurationDemo.RunBatchRegistrationDemo();
                return;
            }
            
            // 检查是否运行快速解析演示
            if (args.Length > 0 && args[0].ToLower() == "fast")
            {
                FastParsingDemo.RunDemo();
                return;
            }
            
            // 检查是否运行简化API演示
            if (args.Length > 0 && args[0].ToLower() == "simple")
            {
                SimplifiedDemo.RunDemo();
                return;
            }

            // 解析命令行参数
            ParseCommandLineArgs(args);

            // 初始化系统资源监控器
            _resourceMonitor = new SystemResourceMonitor();
            
            // 记录测试开始时间
            _testStartTime = DateTime.Now;

            Console.WriteLine("=== DeviceCommons 性能测试控制台 ===");
            Console.WriteLine("随机构建消息并测试各种场景下的性能指标");
            Console.WriteLine($"测试模式: {GetTestModeName()}");
            Console.WriteLine($"加密概率: {_settings.Test.EncryptionProbability:P0}, 压缩概率: {_settings.Test.CompressionProbability:P0}");
            Console.WriteLine("已启用 CPU 和内存监控（千次移动平均）"); // 新增提示
            Console.WriteLine("可用参数: [test|demo|record|table|verify|fix|aes|config|builder|state|fast|simple|default|low|high|stress] - 默认为标准模式");
            Console.WriteLine("  - test: 运行基本功能测试");
            Console.WriteLine("  - demo: 展示数据大小分段和加密压缩细分统计功能");
            Console.WriteLine("  - record: 演示测试记录生成功能");
            Console.WriteLine("  - table: 演示新的横排表格显示效果");
            Console.WriteLine("  - verify: 运行表格对齐修复验证");
            Console.WriteLine("  - fix: 运行性能修复验证");
            Console.WriteLine("  - aes: 运行AES加密器性能对比测试");
            Console.WriteLine("  - config: 演示AES模式配置功能（DeviceCommonsOptions）");
            Console.WriteLine("  - builder: 演示构造器AES模式配置功能（DeviceMessageBuilder）");
            Console.WriteLine("  - state: 演示设备状态配置系统功能");
            Console.WriteLine("  - fast: 演示快速解析工厂模式功能");
            Console.WriteLine("  - simple: 演示简化API接口功能（推荐新用户使用）");
            Console.WriteLine("按 Ctrl+C 退出\n");

            // 设置控制台取消处理
            Console.CancelKeyPress += (sender, e) =>
            {
                e.Cancel = true;
                Console.WriteLine("\n\n正在生成测试记录...");
                
                // 显示最终统计
                DisplayFinalStats();
                
                // 生成测试记录
                GenerateTestRecord();
                
                // 清理资源监控器
                _resourceMonitor?.Dispose();
                
                Environment.Exit(0);
            };

            // 启动性能测试任务
            var performanceTask = Task.Run(PerformanceTestLoop);

            // 启动统计显示任务
            var displayTask = Task.Run(DisplayStatsLoop);

            await Task.WhenAll(performanceTask, displayTask);
        }

        /// <summary>
        /// 解析命令行参数
        /// </summary>
        private static void ParseCommandLineArgs(string[] args)
        {
            if (args.Length == 0) return;

            var mode = args[0].ToLower();
            _settings = mode switch
            {
                "high" or "h" => DefaultConfig.GetHighIntensity(),
                "low" or "l" => DefaultConfig.GetLowIntensity(),
                "stress" or "s" => DefaultConfig.GetStressTest(),
                _ => DefaultConfig.GetDefault()
            };
        }

        /// <summary>
        /// 获取测试模式名称
        /// </summary>
        private static string GetTestModeName()
        {
            if (_settings.Test.IntervalMs == 0 && _settings.Test.EncryptionProbability == 1.0)
                return "压力测试模式";
            if (_settings.Test.IntervalMs == 0 && _settings.Test.EncryptionProbability > 0.6)
                return "高强度模式";
            if (_settings.Test.IntervalMs > 5)
                return "低强度模式";
            return "标准模式";
        }

        /// <summary>
        /// 性能测试主循环
        /// </summary>
        private static async Task PerformanceTestLoop()
        {
            while (true)
            {
                try
                {
                    // 随机生成测试参数
                    var config = GenerateRandomConfig();

                    // 执行性能测试
                    await PerformSingleTest(config);

                    // 短暂延迟避免CPU过载
                    if (_settings.Test.IntervalMs > 0)
                    {
                        await Task.Delay(_settings.Test.IntervalMs);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"测试异常: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 执行单次性能测试
        /// </summary>
        private static async Task PerformSingleTest(TestConfig config)
        {
            var sw = Stopwatch.StartNew();

            // 获取测试开始时的系统资源信息
            var startSnapshot = _resourceMonitor?.GetSnapshot();

            // 1. 构建消息
            var builder = GenerateRandomMessage(config.DeviceName, config.ReadingCount, config.StateCount);
            var buildMessage = builder.Build();
            var buildTime = sw.ElapsedTicks;

            // 2. 序列化
            sw.Restart();
            var buffer = new System.Buffers.ArrayBufferWriter<byte>();
            var hex = _serializer.Serializer(buffer, buildMessage, config.UseEncryption, config.UseCompression, config.Password);
            var serializeTime = sw.ElapsedTicks;

            // 3. 解析
            sw.Restart();
            IDeviceMessage parsedMessage;
            if (config.UseEncryption && !string.IsNullOrEmpty(config.Password))
            {
                // 使用独立Parser实例避免全局状态干扰
                var independentParser = new DeviceMessageParser();
                parsedMessage = independentParser.Parser(hex, config.Password);
            }
            else
            {
                parsedMessage = _parser.Parser(hex);
            }
            var parseTime = sw.ElapsedTicks;

            sw.Stop();

            // 获取测试结束时的系统资源信息
            var endSnapshot = _resourceMonitor?.GetSnapshot();

            // 统计结果
            var result = new TestResult
            {
                Config = config,
                BuildTime = buildTime,
                SerializeTime = serializeTime,
                ParseTime = parseTime,
                MessageSize = hex.Length,
                Success = parsedMessage != null && parsedMessage.MainDevice.DID == config.DeviceName,

                // 添加CPU和内存数据（使用平均值）
                CpuUsagePercent = endSnapshot?.CpuUsagePercent ?? 0.0,
                MemoryUsageBytes = endSnapshot?.MemoryUsageBytes ?? 0L
            };

            // 更新统计信息
            lock (_statsLock)
            {
                _stats.AddResult(result);
            }
        }

        /// <summary>
        /// 生成随机测试配置
        /// </summary>
        private static TestConfig GenerateRandomConfig()
        {
            return new TestConfig
            {
                DeviceName = GenerateRandomDeviceName(),
                ReadingCount = _settings.DataGeneration.ReadingCountRange.GetRandomValue(_random),
                StateCount = _settings.DataGeneration.StateCountRange.GetRandomValue(_random),
                UseEncryption = _random.NextDouble() < _settings.Test.EncryptionProbability,
                UseCompression = _random.NextDouble() < _settings.Test.CompressionProbability,
                Password = GenerateRandomPassword()
            };
        }

        /// <summary>
        /// 生成随机设备名
        /// </summary>
        private static string GenerateRandomDeviceName()
        {
            var prefixes = _settings.DataGeneration.DeviceNamePrefixes;
            var prefix = prefixes[_random.Next(prefixes.Length)];
            var id = _random.Next(1000, 9999);
            return $"{prefix}{id}";
        }

        /// <summary>
        /// 生成随机密码
        /// </summary>
        private static string GenerateRandomPassword()
        {
            var length = _settings.DataGeneration.PasswordLengthRange.GetRandomValue(_random);
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            var password = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                password.Append(chars[_random.Next(chars.Length)]);
            }
            return password.ToString();
        }

        /// <summary>
        /// 生成随机消息
        /// </summary>
        private static IDeviceMessageBuilder GenerateRandomMessage(string deviceName, int readingCount, int stateCount)
        {
            var builder = DeviceMessageBuilder.Create()
                .WithHeader(
                    version: 2,
                    crcType: CRCTypeEnum.CRC16)
                .WithMainDevice(deviceName, (byte)_random.Next(1, 256), config =>
                {
                    for (int i = 0; i < readingCount; i++)
                    {
                        var timeOffset = (short)_random.Next(-1000, 1000);
                        config.AddReading(timeOffset, reading =>
                        {
                            for (int j = 0; j < stateCount; j++)
                            {
                                var sid = (byte)_random.Next(1, 256);
                                var stateValue = GenerateRandomStateValue();
                                reading.AddState(sid, stateValue.Value, stateValue.Type);
                            }
                        });
                    }
                });

            // 随机添加子设备
            if (_random.NextDouble() < 0.3) // 30%概率添加子设备
            {
                var childCount = _random.Next(1, 4); // 1-3个子设备（修复性能问题）
                for (int i = 0; i < childCount; i++)
                {
                    var childName = $"{deviceName}_Child{i + 1}";
                    builder.WithChildDevice(childName, (byte)_random.Next(1, 256), config =>
                    {
                        var childReadingCount = _random.Next(1, 6); // 1-5个读数（修复性能问题）
                        for (int j = 0; j < childReadingCount; j++)
                        {
                            config.AddReading((short)_random.Next(-500, 500), reading =>
                            {
                                var childStateCount = _random.Next(1, 6); // 1-5个状态（修复性能问题）
                                for (int k = 0; k < childStateCount; k++)
                                {
                                    var sid = (byte)_random.Next(1, 256);
                                    var stateValue = GenerateRandomStateValue();
                                    reading.AddState(sid, stateValue.Value, stateValue.Type);
                                }
                            });
                        }
                    });
                }
            }

            return builder;
        }

        /// <summary>
        /// 生成随机状态值
        /// </summary>
        private static (object Value, StateValueTypeEnum Type) GenerateRandomStateValue()
        {
            var typeIndex = _random.Next(8);
            return typeIndex switch
            {
                0 => (GenerateRandomString(), StateValueTypeEnum.String),
                1 => (GenerateRandomBinary(), StateValueTypeEnum.Binary),
                2 => (_random.Next(int.MinValue, int.MaxValue), StateValueTypeEnum.Int32),
                3 => ((short)_random.Next(short.MinValue, short.MaxValue), StateValueTypeEnum.Int16),
                4 => ((ushort)_random.Next(0, ushort.MaxValue), StateValueTypeEnum.UInt16),
                5 => ((float)(_random.NextDouble() * 1000 - 500), StateValueTypeEnum.Float32),
                6 => (_random.NextDouble() * 1000 - 500, StateValueTypeEnum.Double),
                7 => (_random.NextDouble() < 0.5, StateValueTypeEnum.Bool),
                _ => ("DefaultString", StateValueTypeEnum.String)
            };
        }

        /// <summary>
        /// 生成随机字符串
        /// </summary>
        private static string GenerateRandomString()
        {
            var length = _random.Next(1, 51); // 1-50字符
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,!?-_";
            var result = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                result.Append(chars[_random.Next(chars.Length)]);
            }
            return result.ToString();
        }

        /// <summary>
        /// 生成随机二进制数据
        /// </summary>
        private static byte[] GenerateRandomBinary()
        {
            var length = _random.Next(1, 101); // 1-100字节
            var data = new byte[length];
            _random.NextBytes(data);
            return data;
        }

        /// <summary>
        /// 统计信息显示循环
        /// </summary>
        private static async Task DisplayStatsLoop()
        {
            while (true)
            {
                await Task.Delay(_settings.Display.UpdateIntervalMs);

                lock (_statsLock)
                {
                    DisplayCurrentStats();
                }
            }
        }

        /// <summary>
        /// 显示当前统计信息
        /// </summary>
        private static void DisplayCurrentStats()
        {
            Console.Clear();
            Console.WriteLine("  === DeviceCommons 性能测试实时统计 ===");
            Console.WriteLine($"  运行时间: {_stats.GetRunningTime()} | 总测试: {_stats.TotalTests:N0} | 成功率: {_stats.SuccessRate:P2}");
            // 系统资源统计 - 固定列宽表格
            Console.WriteLine("  系统资源统计:");
            Console.WriteLine("┌──────────┬────────────┬────────────┬────────────┬────────────┐");
            Console.WriteLine("│ 资源类型 │   平均值   │  移动平均  │   最小值   │   最大值   │");
            Console.WriteLine("├──────────┼────────────┼────────────┼────────────┼────────────┤");
            Console.WriteLine($"│{"CPU使用率",-5} │{_stats.AverageCpuUsage,8:F1}%   │{_stats.MovingAverageCpuUsage,8:F1}%   │{_stats.MinCpuUsage,8:F1}%   │{_stats.MaxCpuUsage,8:F1}%   │");
            Console.WriteLine($"│{"内存使用",-5} │{_stats.AverageMemoryUsageMB,7:F1} MB  │{_stats.MovingAverageMemoryUsageMB,7:F1} MB  │{_stats.MinMemoryUsageMB,7:F1} MB  │{_stats.MaxMemoryUsageMB,7:F1} MB  │");
            Console.WriteLine("└──────────┴────────────┴────────────┴────────────┴────────────┘");

            // 性能统计 - 固定列宽表格
            Console.WriteLine("  性能统计:");
            Console.WriteLine("┌──────────┬────────────┬────────────┬────────────┬─────────────┐");
            Console.WriteLine("│ 操作类型 │   平均值   │  移动平均  │   最小值   │    最大值   │");
            Console.WriteLine("├──────────┼────────────┼────────────┼────────────┼─────────────┤");
            Console.WriteLine($"│{"构建时间",-5} │{_stats.AverageBuildTime,7:F3} ms  │{_stats.MovingAverageBuildTime,7:F3} ms  │{_stats.MinBuildTime,7:F3} ms  │{_stats.MaxBuildTime,8:F3} ms  │");
            Console.WriteLine($"│{"序列化",-6} │{_stats.AverageSerializeTime,7:F3} ms  │{_stats.MovingAverageSerializeTime,7:F3} ms  │{_stats.MinSerializeTime,7:F3} ms  │{_stats.MaxSerializeTime,8:F3} ms  │");
            Console.WriteLine($"│{"解析时间",-5} │{_stats.AverageParseTime,7:F3} ms  │{_stats.MovingAverageParseTime,7:F3} ms  │{_stats.MinParseTime,7:F3} ms  │{_stats.MaxParseTime,8:F3} ms  │");
            Console.WriteLine("└──────────┴────────────┴────────────┴────────────┴─────────────┘");

            // 数据大小分段解析统计 - 固定列宽表格 
            Console.WriteLine("  数据大小分段解析统计:");
            var segmentStats = _stats.GetParseTimeSegmentStats().ToList();
            if (segmentStats.Any())
            {
                Console.WriteLine("┌───────────────────┬──────────┬────────────┬────────────┬──────────────┬────────────┐");
                Console.WriteLine("│      分段类型     │ 测试次数 │  平均时间  │  移动平均  │   吞吐量     │  平均大小  │");
                Console.WriteLine("├───────────────────┼──────────┼────────────┼────────────┼──────────────┼────────────┤");
                
                foreach (var segment in segmentStats)
                {
                    // 保证每列内容不超出预设宽度
                    var segmentName = segment.SegmentName;
                    Console.WriteLine($"│{segmentName,-15}│{segment.Count,8:N0}  │{segment.AverageParseTime,8:F3} ms │{segment.MovingAverageParseTime,8:F3} ms │{segment.ThroughputKBps,8:F1} KB/s │{segment.AverageDataSize,7:F0}字节 │");
                }
                Console.WriteLine("└───────────────────┴──────────┴────────────┴────────────┴──────────────┴────────────┘");
                
                // 加密对比统计表格 - 固定列宽
                Console.WriteLine("  加密状态对比:");
                var hasEncryptionData = segmentStats.Any(s => s.EncryptedCount > 0 && s.UnencryptedCount > 0);
                if (hasEncryptionData)
                {
                    Console.WriteLine("┌───────────────────┬────────┬──────────┬────────┬────────────┬──────────┬──────────┐");
                    Console.WriteLine("│     分段类型      │加密次数│加密时间ms│不加密数│不加密时间ms│  开销ms  │ 开销比例 │");
                    Console.WriteLine("├───────────────────┼────────┼──────────┼────────┼────────────┼──────────┼──────────┤");
                    
                    foreach (var segment in segmentStats.Where(s => s.EncryptedCount > 0 && s.UnencryptedCount > 0))
                    {
                        var segmentName = segment.SegmentName;
                        var overheadPct = segment.UnencryptedAverageParseTime > 0 ? (segment.EncryptionOverhead / segment.UnencryptedAverageParseTime * 100) : 0;
                        // 限制百分比显示，防止超出列宽
                        var overheadPctStr = Math.Abs(overheadPct) > 99999 ? ">99999%" : $"{overheadPct:F1}%";
                        Console.WriteLine($"│{segmentName,-15}│{segment.EncryptedCount,6:N0}  │{segment.EncryptedAverageParseTime,7:F3}   │{segment.UnencryptedCount,6:N0}  │{segment.UnencryptedAverageParseTime,9:F3}   │{segment.EncryptionOverhead,8:F3}  │{overheadPctStr,9} │");
                    }
                    Console.WriteLine("└───────────────────┴────────┴──────────┴────────┴────────────┴──────────┴──────────┘");
                }
                
                // 压缩对比统计表格
                Console.WriteLine("  压缩状态对比:");
                var hasCompressionData = segmentStats.Any(s => s.CompressedCount > 0 && s.UncompressedCount > 0);
                if (hasCompressionData)
                {
                    Console.WriteLine("┌───────────────────┬────────┬──────────┬──────────┬────────────┬──────────┬──────────┬──────────┐");
                    Console.WriteLine("│      分段类型     │压缩次数│压缩时间ms│不压缩次数│不压缩时间ms│  开销ms  │ 开销比例 │ 压缩比例 │");
                    Console.WriteLine("├───────────────────┼────────┼──────────┼──────────┼────────────┼──────────┼──────────┼──────────┤");
                    
                    foreach (var segment in segmentStats.Where(s => s.CompressedCount > 0 && s.UncompressedCount > 0))
                    {
                        Console.WriteLine($"│{segment.SegmentName,-15}│{segment.CompressedCount,6:N0}  │{segment.CompressedAverageParseTime,8:F3}  │{segment.UncompressedCount,8:N0}  │{segment.UncompressedAverageParseTime,10:F3}  │{segment.CompressionOverhead,8:F3}  │{(segment.CompressionOverhead / segment.UncompressedAverageParseTime * 100),8:F1}% │{segment.CompressionRatio,8:F1}% │");
                    }
                    Console.WriteLine("└───────────────────┴────────┴──────────┴──────────┴────────────┴──────────┴──────────┴──────────┘");
                }
            }
            else
            {
                Console.WriteLine("  暂无分段统计数据");
            }

            // 总体加密压缩对比 - 表格显示
            if ((_stats.EncryptedCount > 0 && _stats.UnencryptedCount > 0) || (_stats.CompressedCount > 0 && _stats.UncompressedCount > 0))
            {
                Console.WriteLine("  总体加密压缩对比:");
                Console.WriteLine("┌────────────┬────────┬──────────┬────────┬──────────┬──────────┬──────────┐");
                Console.WriteLine("│  对比类型  │启用次数│ 启用耗时 │禁用次数│ 禁用耗时 │  开销ms  │ 开销比例 │");
                Console.WriteLine("├────────────┼────────┼──────────┼────────┼──────────┼──────────┼──────────┤");
                
                if (_stats.EncryptedCount > 0 && _stats.UnencryptedCount > 0)
                {
                    Console.WriteLine($"│加密对比    │{_stats.EncryptedCount,6:N0}  │{_stats.EncryptedAverageTime,8:F3}ms│{_stats.UnencryptedCount,6:N0}  │{_stats.UnencryptedAverageTime,8:F3}ms│{_stats.EncryptionOverhead,8:F3}  │{(_stats.EncryptionOverhead / _stats.UnencryptedAverageTime * 100),8:F1}% │");
                }
                
                if (_stats.CompressedCount > 0 && _stats.UncompressedCount > 0)
                {
                    Console.WriteLine($"│压缩对比    │{_stats.CompressedCount,6:N0}  │{_stats.CompressedAverageTime,8:F3}ms│{_stats.UncompressedCount,6:N0}  │{_stats.UncompressedAverageTime,8:F3}ms│{_stats.CompressionOverhead,8:F3}  │{(_stats.CompressionOverhead / _stats.UncompressedAverageTime * 100),8:F1}% │");
                }
                
                Console.WriteLine("└────────────┴────────┴──────────┴────────┴──────────┴──────────┴──────────┘");
                
                // 压缩效果对比
                if (_stats.CompressedCount > 0 && _stats.UncompressedCount > 0)
                {
                    Console.WriteLine("  压缩效果对比:");
                    Console.WriteLine("┌──────────────┬────────────┬────────────┬──────────┐");
                    Console.WriteLine("│  数据类型    │  平均大小  │  平均大小  │ 压缩比例 │");
                    Console.WriteLine("│              │   (压缩)   │  (不压缩)  │          │");
                    Console.WriteLine("├──────────────┼────────────┼────────────┼──────────┤");
                    Console.WriteLine($"│消息大小对比  │{_stats.CompressedAverageSize,7:F0}字符 │{_stats.UncompressedAverageSize,7:F0}字符 │{((1 - _stats.CompressedAverageSize / _stats.UncompressedAverageSize) * 100),8:F1}% │");
                    Console.WriteLine("└──────────────┴────────────┴────────────┴──────────┘");
                }
            }

            // 吞吐量统计 - 表格显示
            Console.WriteLine("  吞吐量统计:");
            Console.WriteLine("┌──────────────┬────────────┐");
            Console.WriteLine("│  统计类型    │   数值/秒  │");
            Console.WriteLine("├──────────────┼────────────┤");
            Console.WriteLine($"│每秒测试次数  │{_stats.TestsPerSecond,10:F1}  │");
            Console.WriteLine("└──────────────┴────────────┘");

            Console.WriteLine("按 Ctrl+C 退出并显示最终统计");
        }

        /// <summary>
        /// 显示最终统计信息
        /// </summary>
        private static void DisplayFinalStats()
        {
            Console.Clear();
            Console.WriteLine("=== DeviceCommons 性能测试最终报告 ===");
            Console.WriteLine($"总运行时间: {_stats.GetRunningTime()}");
            Console.WriteLine($"总测试次数: {_stats.TotalTests:N0}");
            Console.WriteLine($"测试成功率: {_stats.SuccessRate:P2}\n");

            Console.WriteLine("  性能汇总:");
            Console.WriteLine($"CPU: 平均 {_stats.AverageCpuUsage:F1}%, 移动平均 {_stats.MovingAverageCpuUsage:F1}%, 范围 {_stats.MinCpuUsage:F1}%-{_stats.MaxCpuUsage:F1}%");
            Console.WriteLine($"内存: 平均 {_stats.AverageMemoryUsageMB:F1} MB, 移动平均 {_stats.MovingAverageMemoryUsageMB:F1} MB, 范围 {_stats.MinMemoryUsageMB:F1}-{_stats.MaxMemoryUsageMB:F1} MB");
            Console.WriteLine($"构建: 平均 {_stats.AverageBuildTime:F3} ms, 移动平均 {_stats.MovingAverageBuildTime:F3} ms, 范围 {_stats.MinBuildTime:F3}-{_stats.MaxBuildTime:F3} ms");
            Console.WriteLine($"序列化: 平均 {_stats.AverageSerializeTime:F3} ms, 移动平均 {_stats.MovingAverageSerializeTime:F3} ms, 范围 {_stats.MinSerializeTime:F3}-{_stats.MaxSerializeTime:F3} ms");
            Console.WriteLine($"解析: 平均 {_stats.AverageParseTime:F3} ms, 移动平均 {_stats.MovingAverageParseTime:F3} ms, 范围 {_stats.MinParseTime:F3}-{_stats.MaxParseTime:F3} ms\n");
            
            // 数据大小分段解析统计最终报告
            var segmentStats = _stats.GetParseTimeSegmentStats().ToList();
            if (segmentStats.Any())
            {
                Console.WriteLine("  数据大小分段解析性能报告:");
                foreach (var segment in segmentStats)
                {
                    Console.WriteLine($"{segment.SegmentName}: 测试 {segment.Count:N0} 次, 平均 {segment.AverageParseTime:F3} ms, 移动平均 {segment.MovingAverageParseTime:F3} ms, 吞吐量 {segment.ThroughputKBps:F1} KB/s");
                    
                    // 加密状态细分报告
                    if (segment.EncryptedCount > 0 && segment.UnencryptedCount > 0)
                    {
                        Console.WriteLine($"   加密对比: 加密 {segment.EncryptedAverageParseTime:F3} ms vs 不加密 {segment.UnencryptedAverageParseTime:F3} ms (开销 {segment.EncryptionOverhead:F3} ms, {(segment.EncryptionOverhead / segment.UnencryptedAverageParseTime * 100):F1}%)");
                    }
                    
                    // 压缩状态细分报告
                    if (segment.CompressedCount > 0 && segment.UncompressedCount > 0)
                    {
                        Console.WriteLine($"   压缩对比: 压缩 {segment.CompressedAverageParseTime:F3} ms vs 不压缩 {segment.UncompressedAverageParseTime:F3} ms (开销 {segment.CompressionOverhead:F3} ms, {(segment.CompressionOverhead / segment.UncompressedAverageParseTime * 100):F1}%, 压缩比 {segment.CompressionRatio:F1}%)");
                    }
                }
                Console.WriteLine();
            }

            if (_stats.EncryptedCount > 0 && _stats.UnencryptedCount > 0)
            {
                Console.WriteLine("  加密性能影响:");
                Console.WriteLine($"加密开销: {_stats.EncryptionOverhead:F3} ms ({_stats.EncryptionOverhead / _stats.UnencryptedAverageTime * 100:F1}%)\n");
            }

            if (_stats.CompressedCount > 0 && _stats.UncompressedCount > 0)
            {
                Console.WriteLine("  压缩性能影响:");
                Console.WriteLine($"压缩开销: {_stats.CompressionOverhead:F3} ms ({_stats.CompressionOverhead / _stats.UncompressedAverageTime * 100:F1}%)");
                Console.WriteLine($"压缩比: {(1 - _stats.CompressedAverageSize / _stats.UncompressedAverageSize) * 100:F1}%\n");
            }

            Console.WriteLine($"平均吞吐量: {_stats.TestsPerSecond:F1} 测试/秒");
            Console.WriteLine("\n感谢使用 DeviceCommons 性能测试工具！");
        }
        
        /// <summary>
        /// 生成测试记录文档
        /// </summary>
        private static void GenerateTestRecord()
        {
            try
            {
                var generator = new TestRecordGenerator(_stats, _settings, _testStartTime);
                var filePath = generator.GenerateTestRecord();
                
                Console.WriteLine($"\n  测试记录已生成:");
                Console.WriteLine($"   报告文件: {filePath}");
                Console.WriteLine($"   JSON数据: {Path.ChangeExtension(filePath, null).Replace("TestRecord_", "TestData_")}.json");
                Console.WriteLine($"   保存目录: {Path.GetDirectoryName(filePath)}");
                
                Console.WriteLine("\n  测试记录生成完成！");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"\n  生成测试记录时出错: {ex.Message}");
            }
        }
    }
}